<template>
  <div>
    <div style="margin-bottom: 10px">
      <el-input
        style="width: 200px; margin-left: 10px"
        v-model="searchTitle"
        placeholder="请输入公告标题"
        clearable
      >
      </el-input>
      <el-button type="primary" @click="handleSearch" style="margin-left: 5px"
        >搜索</el-button
      >
      <el-button @click="init" style="margin-left: 5px">重置</el-button>
      <el-button
        type="success"
        @click="createNoticeHandle"
        style="margin-left: 20px"
        >添加公告</el-button
      >
    </div>

    <el-table
      :data="notices"
      style="width: 100%"
      :header-cell-style="{
        background: '#f8f8f9',
        height: '60px',
        color: '#000000',
      }"
    >
      <el-table-column prop="id" label="公告序列" width="180"></el-table-column>
      <el-table-column
        prop="title"
        label="公告标题"
        width="180"
      ></el-table-column>
      <el-table-column label="公告内容">
        <template #default="scope">
          {{ scope.row.content.substring(0, 30) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建时间"
        width="210"
      ></el-table-column>
      <el-table-column
        prop="creator"
        label="发布者"
        width="180"
      ></el-table-column>

      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="updateNoticeHandle(scope)"
            >修改</el-button
          >

          <el-popconfirm
            title="你确定要删除吗?"
            @confirm="deleteNoticeHandle(scope)"
          >
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex; justify-content: flex-end; margin-top: 10px">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="notices.length"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        v-model:current-page="currentPage"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog title="添加公告" v-model="dialogVisible" width="30%">
      <el-form
        :model="newNotice"
        :rules="rules"
        ref="noticeForm"
        label-width="80px"
      >
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="newNotice.title"></el-input>
        </el-form-item>

        <el-form-item label="公告内容" prop="content">
          <el-input type="textarea" v-model="newNotice.content"></el-input>
        </el-form-item>

        <el-form-item label="创建人" prop="creator">
          <el-input v-model="newNotice.creator" disabled></el-input>
        </el-form-item>

        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="newNotice.createTime"
            type="datetime"
            placeholder="选择日期时间"
            disabled
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useNoticeStore } from "@/stores/model/notice";
import { useUserStore } from "@/stores/model/user";

const noticeStore = useNoticeStore();
const userStore = useUserStore();

// 示例公告数据
const notices = ref([
  {
    id: "1",
    title: "公告一",
    content: "这是公告一的内容，详细内容如下：...",
    createdAt: "2023-10-01 10:00:00",
    creator: "张三",
  },
]);

const currentPage = ref(1);
const pageSize = ref(5); // 默认每页大小为5

const searchTitle = ref("");
const activeIndex = ref("");
const noticeId = ref(-1);

const isUpdate = ref(false);

const dialogVisible = ref(false);
const newNotice = ref({
  title: "",
  content: "",
  createTime: new Date(),
  creator: "",
});
const noticeForm = ref(null);

// 表单验证规则
const rules = {
  title: [{ required: true, message: "公告标题不能为空", trigger: "blur" }],
  content: [{ required: true, message: "公告内容不能为空", trigger: "blur" }],
  createTime: [
    { required: true, message: "创建时间不能为空", trigger: "change" },
  ],
  creator: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
};

const init = async () => {
  const res = await noticeStore.getNoticeList(
    currentPage.value,
    pageSize.value
  );
  if (res) {
    notices.value = noticeStore.noticeList.rows;
  }
};

onMounted(() => {
  init();
});

const createNoticeHandle = () => {
  dialogVisible.value = true;
  isUpdate.value = false;
  newNotice.value = {
    title: "",
    content: "",
    createTime: new Date(),
    creator: userStore.userInfo.name,
  };
};

const updateNoticeHandle = (scope) => {
  isUpdate.value = true;
  noticeId.value = scope.row.id;
  dialogVisible.value = true;
  activeIndex.value = scope.row.id;
  newNotice.value.title = scope.row.title;
  newNotice.value.content = scope.row.content;
  newNotice.value.createTime = scope.row.createdAt;
  newNotice.value.creator = scope.row.creator;
};

const deleteNoticeHandle = async (scope) => {
  const res = await noticeStore.deleteNotice(scope.row.id);
  if (res) {
    ElMessage.success("删除成功");
    await init();
  }
};

const handleSearch = async () => {
  currentPage.value = 1; // 搜索时重置到第一页
  console.log("搜索条件：", searchTitle.value);
  if (searchTitle.value) {
    const res = await noticeStore.getNoticeListByNoticeTitle(
      searchTitle.value,
      currentPage.value,
      pageSize.value
    );
    if (res) {
      ElMessage.success("查找成功");
      notices.value = noticeStore.noticeList.rows;
    }
  } else {
    ElMessage.error("请输入搜索条件,已进行初始化操作");
    await init();
  }
};

const submitForm = () => {
  noticeForm.value.validate(async (valid) => {
    if (valid) {
      newNotice.value.userId = userStore.userInfo.id;
      let res = false;
      if (!isUpdate.value) {
        res = await noticeStore.createNotice(newNotice.value);
      } else {
        newNotice.value.id = noticeId.value;
        res = await noticeStore.updateNotice(newNotice.value);
      }
      if (res) {
        await init();
        dialogVisible.value = false;
        newNotice.value = {
          title: "",
          content: "",
          createTime: new Date(),
          creator: "",
        };
        ElMessage.success("添加成功");
      }
    } else {
      ElMessage.error("请填写完整的公告信息");
      return false;
    }
  });
};

const handleSizeChange = async (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 改变每页大小时重置到第一页
  await init();
};
</script>

<style scoped></style>
